package com.pandora.credit.service.impl;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NativeHttpClient;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.pandora.credit.dto.push.PushBean;
import com.pandora.credit.service.PushService;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @author developer
 */
@Service
public class PushServiceImpl implements PushService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
            new BasicThreadFactory.Builder().namingPattern("push-schedule-pool-%d").daemon(true).build());
    @Value("${jpush.key.android}")
    private String jpushKeyAndroid;
    @Value("${jpush.secret.android}")
    private String jpushSecretAndroid;
    @Value("${jpush.key.ios}")
    private String jpushKeyIos;
    @Value("${jpush.secret.ios}")
    private String jpushSecretIos;

    private PushPayload buildPushObjectSupport(PushBean pushBean) {
        Notification notification = Notification.newBuilder()
                .addPlatformNotification(AndroidNotification.newBuilder().setAlert(pushBean.getNoticeContent())
                        .setBuilderId(1).setCategory("CATEGORY_SOCIAL").setStyle(1).setTitle(pushBean.getTitle())
                        .setPriority(1).build())
                .addPlatformNotification(IosNotification.newBuilder().setAlert(pushBean.getNoticeContent()).setBadge(pushBean.getBadge()).setSound(pushBean.getSound()).build())
                .build();
        return PushPayload.newBuilder().setPlatform(Platform.all())
                .setAudience(Audience.registrationId(pushBean.getRegistrationIds())).setNotification(notification)
                .setMessage(Message.content(pushBean.getMsgContent()))
                .setOptions(Options.newBuilder().setApnsProduction(true).setTimeToLive(86400).build()).build();
    }

    @Override
    public void sendPush(PushBean pushBean) {
        sendPush(pushBean, jpushKeyAndroid, jpushSecretAndroid);
        sendPush(pushBean, jpushKeyIos, jpushSecretIos);
    }

    private void sendPush(PushBean pushBean, String jpushKey, String jpushSecret) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(jpushSecret, jpushKey, null, clientConfig);
        String authCode = ServiceHelper.getBasicAuthorization(jpushKey, jpushSecret);
        NativeHttpClient httpClient = new NativeHttpClient(authCode, null, clientConfig);
        jpushClient.getPushClient().setHttpClient(httpClient);
        final PushPayload payload = buildPushObjectSupport(pushBean);
        executorService.submit(() -> {
            try {
                PushResult result = jpushClient.sendPush(payload);
                logger.info(result.toString());
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
    }
}
